//
//  YCFileDownLoadManager.m
//  离线下载
//
//  Created by user on 16/4/18.
//  Copyright © 2016年 user. All rights reserved.
//
/*文件名*/
#define  YCFileName [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject ]stringByAppendingPathComponent:self.url.md5String]
/*当前下载长度*/
#define YCCurrentFileLength [[[NSFileManager defaultManager]attributesOfItemAtPath:YCFileName error:nil ][NSFileSize]  integerValue]
// 存储文件总长度的文件路径（caches）
#define YCAllLengthFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"allLength.plist"]

#import "YCFileDownLoadManager.h"
#import "NSString+Hash.h"
@interface YCFileDownLoadManager() <NSURLSessionDataDelegate>
@property(nonatomic,strong)NSOutputStream *stream;
@property(nonatomic,strong)NSURLSession *session;
@property(nonatomic,strong)NSURLSessionDataTask *task;

@property(nonatomic,strong)NSString *url;

@property(nonatomic,copy)complete comPleteBlcok;

@property(nonatomic,assign)NSInteger contentLength;

@property(nonatomic,copy)error error;
@end
@implementation YCFileDownLoadManager
SingleInstanceM

- (void)downLoadWithUrl:(NSString *)url didComplete:(complete)didComplete  comError:(error)diderror
{
    _url = url;
    _comPleteBlcok = didComplete;
    _error = diderror;
    [self.task resume];
    
}
- (void)resumeDownLoad{
    [self.task resume];
}
- (void)suspendDownLoad{
    [self.task suspend];
}
- (void)removeFile
{
    [[NSFileManager defaultManager]removeItemAtPath:YCFileName error:nil];
}
#pragma mark -- NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    [self.stream open];
    self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue]+YCCurrentFileLength;
    /*存入当前文件长度*/
    NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithContentsOfFile:YCFileName];
    if (mutableDic==nil) mutableDic = [NSMutableDictionary dictionary];
    mutableDic[YCFileName]=@(self.contentLength);
    [mutableDic writeToFile:YCAllLengthFullpath atomically:YES];
    
    
    completionHandler(NSURLSessionResponseAllow);
    
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.stream write:data.bytes maxLength:data.length];
    
   // NSLog(@"%f",1.0*YCCurrentFileLength/self.contentLength);
    self.progress = 1.0*YCCurrentFileLength/self.contentLength ;
    self.comPleteBlcok(self.progress,YCFileName);
    
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    
    
    self.error(error);
    [self.stream close];
    self.stream = nil;
    self.session = nil;
    
}
#pragma mark---lazy
- (NSURLSession *)session
{
    
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    }
    return _session;
}
- (NSURLSessionDataTask *)task
{
    if (!_task) {
        
        /*下载完了 不能再下载*/
        NSInteger totalLength = [[NSDictionary dictionaryWithContentsOfFile:YCAllLengthFullpath][YCFileName]  integerValue];
        if (totalLength && totalLength == YCCurrentFileLength) return nil;
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:self.url]];
        _task = [self.session dataTaskWithRequest:request];
        
        
    }
    return _task;
}
- (NSOutputStream *)stream
{
    if (!_stream) {
    
      
        _stream = [[NSOutputStream alloc]initToFileAtPath:YCFileName append:YES];
    }
    return _stream;
    
}
@end
